/**
 * Created by Forcs on 16/4/14.
 */

var model = require('../db/Model');
var co = require('co');
var utils = require('../utils/Utils');
var CachedStore = require('../db/cache/CachedStore');

var StbsManager = function () {
  this._cached = new CachedStore();
};

StbsManager.prototype.findUser = function (stbId, biz, func) {
  var self = this;
  return new Promise(function (resolve, reject) {
    co(function * () {
      var user = self._cached.sget(biz, stbId, function (id, item) {
        return id === item.stbId;
      });
      if (!user) {
        user = yield self.$model.findOne({ stbId: stbId, biz: biz}).exec();
        if (user) {
          self._cached.sput(biz, user);
        }
      }
      var result = user || false;
      if (utils.isFunction(func)) {
        func.call(self, undefined, result);
      }
      resolve(result);
    }).catch(function (err) {
      if (utils.isFunction(func)) {
        func.call(self, err);
      }
      reject(err);
    })
  });
};

module.exports = model.create('Stbs', {
  biz: String,
  stbId: String,
  createAt: String,
  createAtTimestamp: Number
}, { stbId: 1, biz: 1}, StbsManager);